<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

	<%@ page import="java.sql.ResultSet" %>
	<%@ page import="java.sql.SQLException" %>
	<%@ page import="java.sql.Statement" %>
	<%@ page import="java.sql.Connection" %>
	<%@ page import="java.sql.DriverManager" %>
	<%@ page language="java" import="java.lang.*" %>
	<%@ page import = "java.sql.SQLException" %>
	<%@ page import = "com.seniorproject.aims.*" %>
	<%@ page import = "java.util.List" %>
	<%@page import="java.util.ArrayList"%>
	<%@ page import = "java.util.Properties" %>
	<%@ page import = "javax.servlet.ServletContext" %>
	<%@ page import = "java.io.File" %>
	<%@ page import = "java.io.InputStream" %>
	<%@ page import = "java.util.Date" %>
	<%@ page import = "java.text.SimpleDateFormat" %>
	
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Semester Detail</title>
<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" href="css/validation.css" />
	<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css"/>
	<link rel="stylesheet" type="text/css" href="css/table-no-header.css" />
	<script type="text/javascript" src="js/livevalidation_standalone.js"></script> 
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	<script src="js/FileSaver.js"></script>
	<script src="js/jquery-curriculum-detail-wordexport.js"></script>
	
	<link rel="stylesheet" type="text/css" href="css/student-system.css" />
	
	<script type="text/javascript">

 jQuery(document).ready(function($) {
	 
	 $("#word_export").click(function(event) {

			 try{
			 	$("#export-content").wordExport();
	
			 }catch(x){
				 alert(x);
			 }
	

		 });
	
 });
</script>
	
</head>
<body>
<%
//Get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
	//GET PERMISSION

		String name = String.valueOf(session.getAttribute("name"));
		String surname = String.valueOf(session.getAttribute("surname"));
		String role_name = String.valueOf(session.getAttribute("curriculum_role"));
		
		String department_id = String.valueOf(session.getAttribute("department_id"));
				
		System.out.println("name : " + name);///////////////////////////////
		System.out.println("department_id : " + department_id);/////////////////////////
		
		List<String> system_name = new ArrayList<String>();
		
		Permission permission = new Permission(strUser,name);
		permission.setCurriculumCreate(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_create"))));
		permission.setCurriculumDelete(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_delete"))));
		permission.setCurriculumRead(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_read"))));
		permission.setCurriculumUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_update"))));
		
		String permiss = "";
		if(permission.getCurriculumCreate()) {
			permiss = permiss + "Add";
		}
		if(permission.getCurriculumUpdate()) {
			if("".equals(permiss)) {
				permiss = permiss + "Edit";
			} else {
				permiss = permiss + " Edit";
			}
		}
		if(permission.getCurriculumRead()) {
			if("".equals(permiss)) {
				permiss = permiss + "Read";
			} else {
				permiss = permiss + " Read";
			}
		}
		if(permission.getCurriculumDelete()) {
			if("".equals(permiss)) {
				permiss = permiss + "Delete";
			} else {
				permiss = permiss + " Delete";
			}
		}
		
	///////////////////////////////////////////////////////////////////////////////////////////////////////////			
	//check permission
		if(!permission.getCurriculumRead()){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=curriculum_home.jsp"> 	
		<%}
	
	//set Database Connection
		String hostProps = "";
		String usernameProps  = "";
		String passwordProps  = "";
		String databaseProps = "";

		try {
			//get current path
			ServletContext servletContext = request.getSession().getServletContext();
			
			InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
			Properties props = new Properties();
			
			props.load(input);

			hostProps  = props.getProperty("host");
			usernameProps  = props.getProperty("username");
			passwordProps  = props.getProperty("password");
			databaseProps = props.getProperty("database");
		} catch (Exception e) { 
			out.println(e);  
		}

		System.out.println("hostProperties : "+hostProps);////////////////try/////////////////
		System.out.println("usernameProperties : "+usernameProps);////////////////try/////////////////
		System.out.println("passwordProperties : "+passwordProps);////////////////try/////////////////
		System.out.println("databaseProperties : "+databaseProps);////////////////try/////////////////

		// connect database
				Connection connect = null;		
				try {
					Class.forName("com.mysql.jdbc.Driver");
				
					connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
							"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620");//////"&characterEncoding=tis620" Encoding Thai);
				
					if(connect != null){
						System.out.println("Database Connect Sucesses.");
					} else {
						System.out.println("Database Connect Failed.");	
					}
				
				} catch (Exception e) {
					out.println(e.getMessage());
					e.printStackTrace();
				}
				System.out.println("////////////// START DETAILS ///////////////////");//////////////////////////////////////////////////////*/		
				
				// GET information from Curriculum
				String CurriculumId = request.getParameter("CurriculumId");
				String CurriculumNameENOLD = request.getParameter("nameCurriculumEN");
				int DepartmentIdOLD = Integer.parseInt((request.getParameter("departmentId")));
				String departmentOld = new String(request.getParameter("departmentName").getBytes("ISO8859_1"),"UTF-8");
				String YearOLD = request.getParameter("year");
				int Credit = Integer.parseInt(request.getParameter("credit"));
				
				
		//////////////////////////////////////////////////////////////////////////////
		///////////////////////////////SORTING SEMESTER PROGRAM //////////////////////
		//////////////////////////////////////////////////////////////////////////////				
			
			List<Semester> semester = new ArrayList<Semester>();
			List<SemesterCourse> semester_course2 = new ArrayList<SemesterCourse>();
			try {			
			/*Find Semester in DB*/
			
			ResultSet rs_Semester = connect.createStatement().executeQuery("SELECT `year`, `semester`, `semester_program_id`, `curriculum_id`, `credit`"
					+ " FROM semester_program "
					+ " WHERE curriculum_id="+ CurriculumId
					+ " ORDER BY year, semester" );
			
			//Query Previous Information from DB
			while(rs_Semester.next()) {
				
				Semester sem = new Semester();
				
				sem.setCredit(rs_Semester.getInt("credit"));
				sem.setCurriculumId(rs_Semester.getInt("curriculum_id"));
				sem.setSemester(rs_Semester.getInt("semester"));
				sem.setYear(rs_Semester.getInt("year"));
				
				semester.add(sem);
				System.out.println("semester.size=  "+semester.size());
				
			}
					
			}catch (SQLException e) {
				e.printStackTrace();
			}
			
							

%>
	<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right" ><label><font size="4" color="#FFFFFF">  username : <%=strUser %>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label><font size="3" color="#ffffff">log out</font></label></p></a>
					</td>							
				</tr>
			</table>
			
			<div id="main-content-ac">
					
				<div style="padding-left: 980px;">
						<table >
							<tr>
								<td  id="word_export" class="silvergrad" ><span title="Export as Microsoft Word"><img id="word_export_icon" src="image/doc_export_icon.png" style="width:45px; height:38px;cursor: pointer;"></span></td>
							</tr>					
						</table>
				</div>
    <div id="export-content">
			<div id="main-content-ac">
			<center>
				<table style="border-bottom:hidden; border-top:hidden; border-left:hidden; border-right:hidden;">
					<tr style="font-size:26px" align="center">
						<td width="1000px" style="border-bottom:hidden;border-top:hidden;">
							<font size="5">แผนการศึกษา</font>	
						</td>
					</tr>
					<tr style="font-size:26px" align="center">
						<td width="1000px" style="border-bottom:hidden;border-top:hidden;">
							<font size="4">ชื่อหลักสูตร(EN) : <%=CurriculumNameENOLD%></font>	
							<font size="4">| ภาควิชา : วิศวกรรม<%=departmentOld%></font>
						</td>
					</tr>
					<tr style="font-size:26px" align="center">
						<td width="1000px" style="border-bottom:hidden;border-top:hidden;">
							<font size="4">ปี พ.ศ. : <%=YearOLD%></font>
							<font size="4">| จำนวนหน่วยกิต : <%=Credit%> หน่วยกิต</font>
						</td>
					</tr>
				</table>
			</center>	
			</div>
			
			
			<!-- COURSE -->			
			
			<div id="main-content-ac">
			<%				
				int courseCount = 1;
				int checker = 0;
				int counter=0;
				//////////////////////// QUERY YEAR ///////////////////////////
				for(Semester SEM : semester){
					checker = semester.size();
					System.out.println("checker=  "+checker);
			%><center>	
				<table border="0" width="1000px">				
					<tr style="font-size:21px;">					
						<td align="center" rowspan="2" width="66%">ชั้นปีที่ <%=SEM.getYear()%> เทอมที่ <%=SEM.getSemester() %></td>
						<td align="center" rowspan="2" width="10%">หน่วยกิต</td>
						<td align="center" colspan="3" width="24%">จำนวนชั่วโมงรายสัปดาห์</td>
					</tr>
					<tr style="font-size:21px;">						
						<td align="center" width="8%">ทฤษฎี</td>
						<td align="center" width="8%">ปฏิบัติ</td>
						<td align="center" width="8%">ฝึกงาน</td>
					</tr>
					<br><br>
			<%
						/////////////// QUERY COURSE IN SEMESTER /////////////////////////
						
						int i =0;
						/*Find Course in DB*/
						List<Course> course = new ArrayList<Course>();
						List<SemesterCourse> semester_course = new ArrayList<SemesterCourse>();
						
						try{
							ResultSet rs_cour = connect.createStatement().executeQuery("SELECT DISTINCT C.credit,C.lecture_hour,C.lab_hour,C.self_learning_hour, S.course_id, C.course_id"            
																						+",P.semester_program_id,S.semester_program_id,P.curriculum_id,C.curriculum_id, P.year, P.semester"
																						+",S.course_name, S.credit, S.course_id_free_elective, S.semester_program_id, S.index"
									+ " FROM course C, course_semester S, semester_program P"
									+ " WHERE P.semester_program_id = S.semester_program_id AND P.curriculum_id = C.curriculum_id"
									+ " AND P.curriculum_id = "+ CurriculumId+" AND S.course_id = C.course_id AND P.year="+SEM.getYear()+" AND P.semester="+SEM.getSemester()+""
									+ " ORDER BY S.course_id");
							
							while(rs_cour.next()) {
								Course cour = new Course();
								
								cour.setLecture(rs_cour.getInt("C.lecture_hour"));
								cour.setLab(rs_cour.getInt("C.lab_hour"));
								cour.setSelfLearn(rs_cour.getInt("C.self_learning_hour"));										
								cour.setCredit(rs_cour.getInt("C.credit"));
								
								course.add(cour);		
								
								SemesterCourse sem_cou = new SemesterCourse();
								
								sem_cou.setCourseId(rs_cour.getString("S.course_id"));
								sem_cou.setCourseName(rs_cour.getString("S.course_name"));
								sem_cou.setCredit(rs_cour.getInt("S.credit"));
								sem_cou.setElective(rs_cour.getString("S.course_id_free_elective"));
								sem_cou.setSemesterId(rs_cour.getInt("S.semester_program_id"));
								
								semester_course.add(sem_cou);
								System.out.println("semester_course.size=  "+semester_course.size());
							}
							counter++;
							System.out.println("counter=  "+counter);
							
						}catch (SQLException e) {
							e.printStackTrace();
						}
						
						if(counter == checker){
							System.out.println("END LOOP");								
							connect.close();
						}
						
						
						int totalCredit = 0;
						int totalLec = 0;
						int totalLab = 0;
						int totalSelf = 0;
						int total = 0;
//////////////////////////////////////////////////////////////////////////////////////////////////////
						for(SemesterCourse SEM_COU : semester_course){
							
					%>
					
				</table>
				<table border="0" style="border-bottom: hidden;border-top: hidden;" width="1000px">
						<tr style="font-size:20px;">
							<td align="left" width="66%"><%=i+1%>. <%=SEM_COU.getCourseId()%> <%=SEM_COU.getCourseName() %></td>
							<td align="center" width="10%"><%=SEM_COU.getCredit()%></td>
							<td align="center" style="border-bottom: hidden;border-top: hidden;"  width="8%"><%=course.get(i).getLecture() %></td>
							<td align="center" style="border-bottom: hidden;border-top: hidden;"  width="8%"><%=course.get(i).getLab() %></td>
							<td align="center" style="border-bottom: hidden;border-top: hidden;" width="8%"><%=course.get(i).getSelfLearn() %></td>
						
						</tr>	
				</table>
				
				
			<%
							
							totalCredit = totalCredit + SEM_COU.getCredit();
							totalLec = totalLec + course.get(i).getLecture();
							totalLab = totalLab + course.get(i).getLab();
							totalSelf = totalSelf + course.get(i).getSelfLearn();							
							i++;
						}
						%>
							<table border="0" width="1000px" bgcolor="#F2F2F2">
									<tr style="font-size:20px;">
										<td align="center"  width="66%"><font size="3px">รวม</font></td>
										<td align="center"  width="10%"><font size="4px"><%=totalCredit%></font></td>
										<td align="center" width="8%"><font size="4px"><%=totalLec%></font></td>
										<td align="center" width="8%"><font size="4px"><%=totalLab%></font></td>
										<td align="center" width="8%"><font size="4px"><%=totalSelf%></font></td>
									</tr>		
							</table>
						<%
							total = totalLec+totalLab+totalSelf;
						%>
							<table border="0" width="1000px" style="border-top: hidden;">
									<tr style="font-size:20px;">
										<td align="center"  width="10%"><font size="4px"><%=totalCredit%> หน่วยกิต  <%=total %> ชั่วโมง / สัปดาห์</font></td>										
									</tr>		
							</table>
						
						<%
				}
			%>
				
				
			</center>
			</div>	
					
				
				<div style="clear: both;"></div>
				<br><br>
				
				 <form id="form" name="form" method="post" action="curriculum_add_schedule.jsp">	
										<input type="hidden" id="checker2" name="checker2" value="none" />	
										<input type="hidden" id="checker" name="checker" value="none" />
										
										<input type="hidden" id="CurriculumId" name="CurriculumId" value="<%=CurriculumId%>" />
										<input type="hidden" id="nameCurriculumEN" name="nameCurriculumEN" value="<%=CurriculumNameENOLD%>" />
										<input type="hidden" id="departmentId" name="departmentId" value="<%=DepartmentIdOLD%>" />
										<input type="hidden" id="departmentName" name="departmentName" value="<%=departmentOld%>" />
										<input type="hidden" id="year" name="year" value="<%=YearOLD%>" />						
										<input type="hidden" id="credit" name="credit" value="<%=Credit%>" />		
										
										<input type="hidden" id="YearSemester" name="YearSemester" value="0" />	
										<input type="hidden" id="TermSemester" name="TermSemester" value="0" />		
										<input type="hidden" id="CreditSemester" name="CreditSemester" value="0" />
										
										<input type="hidden" id="delete" name="delete" value="none" />	
										<input type="hidden" id="sysID" name="sysID" value="none" />
																				
										<td><center><input type="submit" value="back" class="buttonStyle" /></center></td>
				</form>
				
					<div id="footer"></div>
			</div>
			 
					<div style="clear: both;"></div>
		</div>	
	</div>
</body>
</html>